package com.sk.sourcecircle.activity.mine.act;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.sk.sourcecircle.R;
import com.sk.sourcecircle.base.BaseActivity;
import com.sk.sourcecircle.callback.HandleDataCallBack;
import com.sk.sourcecircle.dialog.DialogFramentUploadPhoto;
import com.sk.sourcecircle.dialog.SexDialogFragment;
import com.sk.sourcecircle.entity.HomePageInfo;
import com.sk.sourcecircle.entity.UploadSuccess;
import com.sk.sourcecircle.utils.AppApi;
import com.sk.sourcecircle.utils.HttpAddress;
import com.sk.sourcecircle.utils.MD5;
import com.sk.sourcecircle.utils.MyUtils;
import com.sk.sourcecircle.utils.SnackUtils;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by sk on 2017/11/22.
 */

public class MySettingsActivity extends BaseActivity implements HandleDataCallBack {
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.next)
    ImageView next;
    @BindView(R.id.change_head)
    RelativeLayout changeHead;
    @BindView(R.id.ed_name)
    EditText edName;
    @BindView(R.id.ed_phone)
    TextView edPhone;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.ed_location)
    EditText edLocation;
    @BindView(R.id.ed_descibe)
    EditText edDescibe;
    @BindView(R.id.head)
    ImageView head;

    private HomePageInfo.DataBean.UserInfoBean myInfo;
    private int sex;

    private static String path = "/sdcard/yq/";//sd路径


    public int getSex() {
        return sex;
    }

    public void setSex(int sex) {
        this.sex = sex;
        if (sex == 0) {
            tvSex.setText("男");
        } else {
            tvSex.setText("女");
        }
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_my_settings;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myInfo = getIntent().getParcelableExtra("data");
        Glide.with(mContext).load(myInfo.getHead_url()).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(head);
        edName.setText(myInfo.getNickname());
        if (myInfo.getIntroduce() != null) {
            edDescibe.setText(myInfo.getIntroduce());
        }
        if (myInfo.getAddress() != null) {
            edLocation.setText(myInfo.getAddress());
        }
        if (myInfo.getPhone() != null) {
            edPhone.setText(myInfo.getPhone());
        }
        sex = myInfo.getGender();
        if (myInfo.getGender() == 0) {
            tvSex.setText("男");
        } else {
            tvSex.setText("女");
        }
    }

    @OnClick({R.id.back, R.id.change_head, R.id.tv_sex, R.id.save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.change_head:
                checkPermission();
                DialogFramentUploadPhoto dialogFramentUploadPhoto = new DialogFramentUploadPhoto();
                dialogFramentUploadPhoto.setMyCallBack(MySettingsActivity.this);
                dialogFramentUploadPhoto.show(getFragmentManager(), "photo");

                break;
            case R.id.tv_sex:
                SexDialogFragment sexDialogFragment = new SexDialogFragment();
                sexDialogFragment.show(getSupportFragmentManager(), "sex");
                break;
            case R.id.save:
                AppApi.changePersonInfo(edLocation.getText().toString(), edDescibe.getText().toString(), sex, edName.getText().toString(), edPhone.getText().toString(), MySettingsActivity.this, 0, MySettingsActivity.this);
                break;
        }
    }

    void checkPermission() {
        final List<String> permissionsList = new ArrayList<>();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if ((checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED))
                permissionsList.add(Manifest.permission.CAMERA);
            if ((checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED))
                permissionsList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if ((checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED))
                permissionsList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            if (permissionsList.size() != 0) {
                requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                        10);
            }
        }
    }

    public void startCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                "head.jpg")));
        startActivityForResult(intent, 1);//采用ForResult打开
    }

    public void ChoosePhoto() {
        Intent intent1 = new Intent(Intent.ACTION_PICK, null);
        intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent1, 2);
    }

    @Override
    public void takePhoto() {
        super.takePhoto();
        startCamera();
    }

    @Override
    public void choosePhoto() {
        super.choosePhoto();
        ChoosePhoto();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            switch (requestCode) {
                case 1:
                    File temp = new File(Environment.getExternalStorageDirectory()
                            + "/head.jpg");
                    cropPhoto(Uri.fromFile(temp));//裁剪图片
                    break;
                case 2:
                    cropPhoto(data.getData());//裁剪图片

                    break;
                case 3:
                    if (data != null) {
                        Bundle extras = data.getExtras();
                        Bitmap bitmap = extras.getParcelable("data");
                        try {
                            File userPic = setPicToView(bitmap);//保存在SD卡
                            upLoadAppendixImg(userPic);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
            }
        }

    }

    public void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
    }

    private void upLoadAppendixImg(final File file) {
        RequestParams requestParams = new RequestParams(HttpAddress.TestIp + HttpAddress.ChangeHead);
        requestParams.addHeader("Content-Type", "multipart/form-data");
        requestParams.setMultipart(true);
        long timeStamp = System.currentTimeMillis();
        requestParams.addBodyParameter("timestamp", String.valueOf(timeStamp));
        requestParams.addBodyParameter("sign", MD5.md5(timeStamp + "_yuanquan"));
        requestParams.addBodyParameter("image", file);
        requestParams.addBodyParameter("token", MyUtils.getToken(mContext));
        requestParams.addBodyParameter("user_id", String.valueOf(MyUtils.getCode(mContext)));
        x.http().post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.v("upLoadAppendixImg", result);
                SnackUtils.show(mRootView, "头像修改成功了哦~");
                UploadSuccess jsonObject = JSON.parseObject(result, UploadSuccess.class);
                Glide.with(mContext).load(jsonObject.getData().getImage()).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(head);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.v("upLoadAppendixImg", ex.toString());
                SnackUtils.showError(mRootView, "sorry，头像上传失败，请重试哦~~");

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private File setPicToView(Bitmap mBitmap) throws IOException {
        //创建目录
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        //创建文件
        file = new File(path + "head.jpg");
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return file;
    }

    @Override
    public void handlerSuccessData(String result, int tag) {
        Toast.makeText(mContext, "信息保存成功！", Toast.LENGTH_SHORT).show();
        setResult(RESULT_OK);
        finish();
    }

    @Override
    public void handlerFailData(String failString, int tag) {

    }

    @Override
    public void handleErrorData(String error, int tag) {

    }
}
